<?php
/**
 * 后台上传图片控制器。
 *
 * @author    Fairyin <fairyin@126.com>
 * @copyright © 2016 www.imcn.vip
 * @version   v1.0
 */

namespace App\Http\Controllers\Shadow;

require __DIR__.'/../../../../vendor/autoload.php';

use View;
use Config;
use Illuminate\Http\Request;
// 引入鉴权类
use Qiniu\Auth;
// 引入上传类
use Qiniu\Storage\UploadManager;

class ImageUploadController extends ShadowController
{
    public function onGet()
    {
        $this->results['token'] = csrf_token();
        
        return View::make('shadow/upload', $this->results);
    }
    
    public function upload(Request $request)
    {
        $a_qiniu = Config::get('services.qiniu');
        if (!is_array($a_qiniu) || !isset($a_qiniu['ak']) || !isset($a_qiniu['sk']) || !isset($a_qiniu['bucket'])) {
            return false;
        }
        // 构建鉴权对象
        $auth = new Auth($a_qiniu['ak'], $a_qiniu['sk']);
        // 生成上传 Token
        $s_token = $auth->uploadToken($a_qiniu['bucket']);
        if (!isset($_FILES["img"]['tmp_name']) || $_FILES["img"]['size'] <= 0) {
            return false;
        }
        $filePath = $_FILES["img"]['tmp_name'];
        // 上传到七牛后保存的文件名
        $s_type = $request->get('type', 'detail');
        $key = date('ymd', time()) . '/' . time();
        if ($s_type == 'cover') {
            $key = 'cover/' . time() . '.jpg';
        } else {
            $key = $request->get('key', $key);
        }
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        $a_result = $uploadMgr->putFile($s_token, $key, $filePath);
        if (isset($a_result[0]['hash']) && isset($a_result[0]['key'])) {
            $a_result[0]['ext'] = 'endwise';
            $a_infos = getimagesize($_FILES["img"]['tmp_name']);
            if (isset($a_infos[0]) && isset($a_infos[1])) {
                if ($a_infos[0] > $a_infos[1]) {
                    $a_result[0]['ext'] = 'crossrange';
                }
            }
            
            return $this->ajaxSuccess($a_result[0]);
        }
        
        return $this->ajaxError(array('reason' => '图片上传失败！'));
    }
}
